package com.north.light.libcommon.utils;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Build;

/**
 * Created by lzt
 * time 2020/5/12
 * 描述：闪光灯工具类
 */
public class LightUtils {

    private volatile boolean isLighting = false;//是否打开闪光灯标识
    private Context mContext;
    private Camera mCamera;

    private static final class SingleHolder {
        static LightUtils mInstance = new LightUtils();
    }

    public static LightUtils getInstance() {
        return SingleHolder.mInstance;
    }

    public void init(Context context) {
        this.mContext = context.getApplicationContext();
    }

    /**
     * 打开
     * */
    public void turnOn() {
        if (isLighting) {
            return;
        }
        changeFlashLight(true);
    }

    /**
     * 关闭
     * */
    public void turnOff() {
        if (!isLighting) {
            return;
        }
        changeFlashLight(false);
    }

    /**
     * 安卓7.0兼容问题适配
     */
    private void changeFlashLight(boolean result) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
            String[] ids = new String[0];
            try {
                ids = manager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = manager.getCameraCharacteristics(id);
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
                    if (flashAvailable != null && flashAvailable
                            && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                        manager.setTorchMode(id, result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //7.0以下
            if (mCamera == null) {
                mCamera = Camera.open();
            }
            Camera.Parameters parameters = mCamera.getParameters();
            if (result) {
                //打开
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mCamera.setParameters(parameters);
            } else {
                //关闭
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(parameters);
            }
        }
        isLighting = result;
    }

    public void release() {
        changeFlashLight(false);
        if (mCamera != null) {
            mCamera.release();
        }
        mCamera = null;
    }
}
